package com.app.ui.fragment

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.app.model.News
import com.app.NewsApplication
import com.app.NewsApplication.Companion.loginUser
import com.app.R
import com.app.ui.adapter.NewsAdapter
import com.app.ui.adapter.NewsAdapter.Companion.FAILED
import com.app.ui.adapter.NewsAdapter.Companion.FINISHED
import com.app.ui.adapter.NewsAdapter.Companion.HAS_MORE
import com.app.util.DBOpenHelper
import com.app.util.showToast
import java.lang.Exception
import java.util.*
import kotlin.concurrent.thread

/**
 * 新闻碎片：newType是拼音,用于url  category是汉字,用于sql
 */
class SearchFragment(private val input: String) : Fragment() {
    // 注意:通过构造方法为Fragment传递参数很不优雅，在Fragment restore的时候就会丢失参数。
    // 一般推荐通过将参数设置到Bundle里面，然后调用fragment.setArguments方法传递参数，这样可以保证系统恢复Fragment是还能拿到传入的参数。

    private lateinit var newsRecyclerView: RecyclerView

    private lateinit var swipeRefreshLayout: SwipeRefreshLayout

    /**
     * 成员变量 newsList 作为视图中 newsRecyclerView 的 dataSet
     */
    private val newsList = ArrayList<News>()

    private val newsAdapter = NewsAdapter(newsList, this)

    /**
     *  成员变量 isLoading 作为一个标记,保证 loadNewData() 和 loadCacheData() 这两个函数同一时间只有一个正在执行
     */
    private var isLoading = false

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_news, container, false)
        newsRecyclerView = view.findViewById(R.id.news_recycler_view)
        swipeRefreshLayout = view.findViewById(R.id.news_refresh)
        return view
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        newsRecyclerView.layoutManager = LinearLayoutManager(NewsApplication.context)
        newsRecyclerView.adapter = newsAdapter

        loadSearchData()

        swipeRefreshLayout.setColorSchemeColors(Color.parseColor("#03A9F4"))
        swipeRefreshLayout.setOnRefreshListener {
            thread {
                Thread.sleep(700) // 这个延迟0.7秒只是为了实现视觉效果，与逻辑无关
                activity?.runOnUiThread {
                    loadSearchData()
                    swipeRefreshLayout.isRefreshing = false // 让圆形进度条停下来
                }
            }
        }
    }

    private fun loadSearchData() {
        if (isLoading) return
        isLoading = true
        thread {
            val collectionFromDatabase = getSearchFromDatabase()
            // 刷新UI
            activity?.runOnUiThread {
                replaceDataInRecyclerView(collectionFromDatabase)
                newsAdapter.footerViewStatus = FINISHED
                isLoading = false
            }
        }
    }

    private fun getSearchFromDatabase(): List<News> {
        val dbOpenHelper = DBOpenHelper(this.activity)
        return dbOpenHelper.getMySearch(input)
    }

    /**
     * 刷新UI操作:用 newData 替换掉 RecyclerView中所有的旧数据
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun replaceDataInRecyclerView(newData: List<News>) {
        try {
            newsList.clear()
            newsList.addAll(newData)
            newsAdapter.notifyDataSetChanged()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}